<?php

namespace plugin\webman\gateway2;
use support\Db;
use GatewayWorker\Lib\Gateway;
use support\Redis;
use plugin\webman\common\Common;

// 斗猿场公共方法
class Method2
{
    static function robotmove(){
        $robots =  Db::table("wa_users")->where(['isrobot'=>1,'roomid'=>0])->get()->toArray();
    
        $list_robots = Common::object_array($robots);
        $expect = Common::getnowexpect();
        // 每次挪动几个机器人
        $nums = rand(2,6);
        $arr = array_rand($list_robots,$nums);
        // var_dump($arr);die;
        foreach($arr as $keyt){
            $list[] = $list_robots[$keyt];
        }
        // var_dump($list);die;
        $list_robots = $list;
        foreach($list_robots as $k =>$v){
            // 记录机器人当前位置
            $keykill = 'dyc_killer_'.$expect;
            $killerposition= Redis::get($keykill);
            if($killerposition==''){
                $killerposition=0;
            }
            $key = "dyc_robotpositon_".$expect.'_'.$v['id'];
            $to['smallroomid']=self::getrobottouzhuroomid($killerposition);
            if($to['smallroomid']==''){
                $to['smallroomid']=rand(0,13);
            }

            // var_dump($killerposition,$to['smallroomid']);die;

            Redis::set($key,$to['smallroomid']);
            $to['uid']=(string)$v['id'];
           
                $res2=[
                    'code'=>1,
                    'msg'=>'用户投注挪动了小房间位置',
                    'info'=>$to
                ];               
            // 广播机器人位置变化信息
            // Gateway::sendToGroup(1,Common::returndata('usertouzhu',$res2));
            Gateway::sendToAll(Common::returndata('usertouzhu',$res2));
            // 机器人模拟投注   并广播房间内投注数据变化
            $config =self::getbaseconfig();
            // var_dump($config);die;
            // $coin = rand($config['logo']['robotmin'],$config['logo']['robotmax']);
            $coin = rand(1,10);
            $touzhu=[
                'uid'=>$v['id'],
                'expect'=>$expect,
                'tzid'=>$to['smallroomid'],
                'tzname'=>self::smallroomname($to['smallroomid']),
                'coin'=>$coin,
                'addtime'=>date('Y-m-d H:i:s',time()),
                'status'=>0,
                'roomid'=>2,
                'isrobot'=>1,
                'gametype'=>'dyc'
            ];
            $iftouzhu = Db::table("wa_touzhu")->where(['expect'=>$expect,'uid'=>$v['id'],'gametype'=>'dyc'])->first();
            if($iftouzhu){
                $del = Db::table("wa_touzhu")->where(['expect'=>$expect,'uid'=>$v['id'],'gametype'=>'dyc'])->update(['ifyouxiao'=>0]);
               
            }
                
            $in = Db::table("wa_touzhu")->insert($touzhu);
            
            // 发送群组socket 更新房间内
            $res=[
                'code'=>1,
                'msg'=>'小房间投注总额更新',
                'info'=>self::getroom_coin_list(2,$expect)
            ];
            
            Gateway::sendToGroup(2,Common::returndata('updatesmallcoin',$res));
        }
        
    }

    static function getrobottouzhuroomid($killerposition){
        $position = rand(0,13);
        if($position==$killerposition){
            self::getrobottouzhuroomid($killerposition);
        }else{
            return $position;
        }
    }
    static function getbaseconfig(){
        $config = Db::table("wa_options")->where("name","system_config")->select("value")->get();
        $config= json_decode($config,1);
        $config = json_decode($config[0]['value'],1);
        return $config;
    }

    // 获取小房间的名字
    public static function smallroomname($id){
        switch ($id) {
            case '0':
                $name = "x0y0";  //左下角为x0y0
                break;
            case '1':
                $name = "x0y1";
                break;
            case '2':
                $name = "x0y2";
                break;
            case '3':
                $name = "x0y3";
                break;
            case '4':
                $name = "x0y4";
                break;
            case '5':
                $name = "x1y4";
                break;
            case '6':
                $name = "x2y4";
                break;
            case '7':
                $name = "x3y4";
                break;
                
            case '8':
                $name = "x4y3";
                break;
            case '9':
                $name = "x4y2";
                break;
            case '10':
                $name = "x4y1";
                break;
            case '11':
                $name = "x4y0";
                break;
            case '12':
                $name = "x3y0";
                break;
            case '13':
                $name = "x2y0";
                break;
            case '14':
                $name = "x1y0";
                break;       
          
        }
        // var_dump($id,$name);
        $result = isset($name) ? $name : '';
        return $result;
    }

     // 计算杀手去哪个房间
     static function killer(){
        // $expect = Common::getnowexpect();
        
        // // $room['killer_to_smallroomid'] = (int)1;
        // $key = 'dyc_killer_'.$expect;
        // $room['killer_to_smallroomid'] = Redis::get($key);
        // if($room['killer_to_smallroomid']==''){
        //     $room['killer_to_smallroomid'] =0;
        // }
        // // 上期杀手在哪个位置
        // $key2 = 'dyc_killer_'.($expect-1);
        // $room['killer_to_smallroomid_shangqi'] = Redis::get($key2);
        // // var_dump("room");
        // // var_dump($room);
        // if(!$room['killer_to_smallroomid']){
        //     $room['killer_to_smallroomid'] = self::getkillertoroom($room['killer_to_smallroomid_shangqi']);  //开出的房间号    需要更新为控制开奖
        //     Redis::set($key,$room['killer_to_smallroomid']); 
        //     $record = [
        //         'samllroomid'=> $room['killer_to_smallroomid'],
        //         'roomname'=>self::smallroomname($room['killer_to_smallroomid']),
        //         'expect'=>$expect,
        //         'addtime'=>date('Y-m-d H:i:s',time())
        //     ];
        //     Db::table("wa_killer_record")->insert($record);

        //     // 把每个投注记录 改掉杀手的结果
        //     $touzhus = Db::table("wa_touzhu")->where(['expect'=>$expect,'gametype'=>'dyc'])->get();
        //     $touzhu = Common::object_array($touzhus);
        //     if($touzhu){
        //         $handle = self::handlekiller($touzhu,$expect,$room['killer_to_smallroomid']);
        //     }
        //     $room['killer_to_smallroomid_shangqi'] = Redis::get($key2);
        //     // 发放瓜分的收益
        //     // 查询本期 所有投注的人
        //     $guafen = (int)Db::table("wa_touzhu")->where(['expect'=>$expect,'tzid'=>$room['killer_to_smallroomid']])->sum("coin"); //本期 杀手 瓜分金额
        //     if($guafen>0){
        //         $allpeople = (int)Db::table("wa_touzhu")->where(['expect'=>$expect])->count(); //本期 投注人数
        //         $pingjun = $guafen/$allpeople;

        //         $tzlist = Db::table("wa_touzhu")->where(['expect'=>$expect,'isrobot'=>0,'gametype'=>'dyc'])->get()->map(function ($value) {return (array)$value;})
        //         ->toArray();
        //         // $tz = Common::object_array($tzlist);
        //         // var_dump($tz);die;
        //         if($tzlist){

        //             foreach($tzlist as $k=>$v){
        //                 if($v['status']==1){
        //                     self::updateusercoin($v['uid'],$pingjun,1);
        //                     Db::table("wa_touzhu")->where(['id'=>$v['id']])->update(['rewards'=>$pingjun]);
        //                     Db::table("wa_usercoin_record")->insert([
        //                         'uid'=>$v['uid'],
        //                         'coin'=>$pingjun,
        //                         'type'=>1,
        //                         'remark'=>'本期 投注 瓜分',
        //                         'addtime'=>date("Y-m-d H:i:s")
        //                     ]);
        //                 }
                        
        //             }
        //         }

        //     }
           
        // }else{
        //     $room['tzcoin'] = (int)Db::table("wa_touzhu")->where(['expect'=>$expect,'tzid'=>$room['killer_to_smallroomid']])->sum("coin");
        //     return $room;
        // }
        
        // // 得改为每个房间的开奖

        
        // $room['tzcoin'] = (int)Db::table("wa_touzhu")->where(['expect'=>$expect,'tzid'=>$room['killer_to_smallroomid']])->sum("coin");
        // return $room;
    }


    // 操作用户金币   type : 0 减少  ；  1增加
    static function updateusercoin($uid,$coin,$type ){
        $userinfo = Common::getuserinfo($uid);
        if($type==0){
            $newcoin = $userinfo['coin']-$coin;
        }else{
            $newcoin = $userinfo['coin']+$coin;
        }
        
        $up = Db::table("wa_users")->where("id",$uid)->update(['score'=>$newcoin]);
        if($up){
            return 1;
        }else{
            return 0;
        }
    
    }
    // 获取当前杀手前往的房间，上次的房间号不能与现在开出来的相同
    static function getkillertoroom($shangqi){
        $roomid =rand(0,13);
        if($roomid!=$shangqi){
            return $roomid;
        }else{
            self::getkillertoroom($shangqi);
        }
    }

       // 处理开奖事宜
    static function handlekiller($list,$expect,$roomid){
       
        $roomname = self::smallroomname($roomid);
        foreach ($list as $k =>$v){
            // var_dump($v);
            // if($v['tzid']==$roomid){
            //     $up = Db::table("wa_touzhu")->where(['id'=>$v['id'],'ifyouxiao'=>1])->update(['resultid'=>$roomid,'resultname'=>$roomname,'status'=>1]);
            // }else{
            //     $up = Db::table("wa_touzhu")->where(['id'=>$v['id'],'ifyouxiao'=>1])->update(['resultid'=>$roomid,'resultname'=>$roomname,'status'=>2]);
            // }

        }
    }

    // 获取当前房间内某一期的投注金额 小房间金额列表
    static function getroom_coin_list($roomid,$expect){
        for($i=0;$i<14;$i++){
            $room['smallroomid']=$i;
            $room['allcoin'] =  (int)Db::table("wa_touzhu")->where(['roomid'=>$roomid,'tzid'=>$i,'expect'=>$expect,'ifyouxiao'=>1,'gametype'=>'dyc'])->sum("coin");
            $new[]=$room;
        }
        return $new;
    }
    // 获取当前房间人数
    static function getroom_nums($roomid){
        $key = "roomnums_".$roomid;  //房间人数key
        $nums = Redis::get($key);
        if(!$nums){
            Redis::set($key, 0);
            return 0;
        }
        return $nums;
    }
    // 进入房间
    static function enterroom($client_id,$roomid,$userinfo){
        // 设备绑定UID
        $key = 'binduid_'.$client_id;  //绑定uid写入redis
        $useredis = Redis::set($key,$userinfo->id);
        Gateway::bindUid($client_id,$userinfo->id);
        // socket 加入群组
        Gateway::joinGroup($client_id, 1);
        // 更新用户所在房间
        self::changeuserroomid($userinfo->id,$roomid);
        // 增加房间在线人数
        self::uproom_nums($roomid,1,1);

    }
    // 获取人员房间位置信息
    static function getposition($uid){
        $expect = Common::getnowexpect();
        $key = "dyc_robotpositon_".$expect.'_'.$uid; 
        $p = Redis::get($key);
        if(!$p){
            return "0";
        }else{
            return $p;
        }
    }
    // 更新用户所在房间信息
    static function changeuserroomid($uid,$roomid){
        Db::table("wa_users")->where("id",$uid)->update(['roomid'=>$roomid]);
    }

      // 增加房间在线人数  type:0 减少；  1增加；    num 执行数量
    static function uproom_nums($roomid,$type,$num){
        $key = "roomnums_".$roomid; 
        $nums = Redis::get($key);
        if($type==1){
            if(!$nums){
                Redis::set($key, 1);
                return 1;
            }else{
                
                $nums2 = intval($nums)+intval($num);
                Redis::set($key, $nums2);
                return $nums;
            }
        }else{
            if(!$nums){
                Redis::set($key, 0);
                return 1;
            }else{
                if($nums>$num){
                    $nums = intval($nums)-intval($num);
                }else{
                    $nums = 0;
                }
                
                Redis::set($key, $nums);
                return $nums;
            }
        }
    }  

    static function joinrobots(){
        $robots =  Db::table("wa_users")->where(['isrobot'=>1,'roomid'=>0])->get()->toArray();
        $list_robots = Common::object_array($robots);
        foreach($list_robots as $k=>$v){
            $v['client_id']="7f00000108ff00000003";
            $v['uid']=(string)$v['id'];
            $v['userinfo']=Common::getuserinfo($v['id']);
            // 增加每个人的位置信息
            $v['position']=self::getrobotposition($v['id']);
            $new[]=$v;
        }
        return $new;
    } 
    // 获取机器人位置信息
    static function getrobotposition($uid){
        // var_dump($uid);
        $expect = Common::getnowexpect();
        $key = "dyc_robotpositon_".$expect.'_'.$uid;
    
        $p = Redis::get($key);
        // var_dump($p);
        if($p==''){
            return "15";
        }else{
            return $p;
        }
    }    
    // 离开房间

    static function leaveroom($client_id,$roomid,$userinfo){

        // socket 离开群组
        Gateway::leaveGroup($client_id, $roomid);
        // 更新用户所在房间
        self::changeuserroomid($userinfo['id'],0);
        // 减少房间在线人数
        self::uproom_nums($roomid,0,1);

    }
     

    // 获取我的投注记录
    static function getmytzinfo($uid){
        $info['allcoin']=(string)Db::table("wa_touzhu")->where(['uid'=>$uid,'ifyouxiao'=>1])->sum("coin");
        $info['reward']=(string)Db::table("wa_touzhu")->where(['uid'=>$uid,'ifyouxiao'=>1,'status'=>1])->sum("rewards");
        $info['list']=Db::table("wa_touzhu")->where(['uid'=>$uid,'ifyouxiao'=>1])->orderByDesc('id',true)->limit(60)->get();
        return $info;
    }
    // 更新人员小房间位置信息
    static function upposition($uid,$smallroomid){
        $expect = Common::getnowexpect();
        $key = "position_".$uid; 
        Redis::set($key, $smallroomid);
    }
}